package jnpf.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.PathNotFoundException;
import jnpf.model.dify.talk.resp.DifyEndResp;

import java.io.IOException;
import java.util.*;

/**
 * json path 工具
 */
public class JsonUtils {
   /**
    * 判断json字符串中是否存在某个key
    * @param jsonStr json字符串
    * @param jsonPath json path
    **/
    public static boolean keyExists(String jsonStr, String jsonPath) {
        try {
            JsonPath.read(jsonStr, jsonPath);
            return true;
        } catch (PathNotFoundException e) {
            return false;
        }
    }

    /**
     * 从 JsonNode 中获取指定字段的值，并根据类型进行转换
     *
     * @param jsonNode  JsonNode 对象
     * @param fieldName 字段名
     * @param clazz     字段类型
     * @param <T>       泛型类型
     * @return 转换后的值，如果字段为空或转换失败则返回 null
     */
    @SuppressWarnings("unchecked")
    public static <T> T getFieldValue(JsonNode jsonNode, String fieldName, Class<T> clazz) {
        if (Objects.isNull(jsonNode) || jsonNode.get(fieldName) == null || jsonNode.get(fieldName).isNull()) {
            if (clazz == Integer.class) {
                return (T) Integer.valueOf(0);
            } else if (clazz == Long.class) {
                return (T) Long.valueOf(0L);
            } else if (clazz == Boolean.class) {
                return (T) Boolean.FALSE;
            } else if (clazz == Double.class) {
                return (T) Double.valueOf(0.0);
            }
            return null;
        }

        JsonNode fieldNode = jsonNode.get(fieldName);
        if (clazz == String.class) {
            return (T) fieldNode.asText();
        } else if (clazz == Integer.class) {
            return (T) Integer.valueOf(fieldNode.asInt());
        } else if (clazz == Long.class) {
            return (T) Long.valueOf(fieldNode.asLong());
        } else if (clazz == Boolean.class) {
            return (T) Boolean.valueOf(fieldNode.asBoolean());
        } else if (clazz == Double.class) {
            return (T) Double.valueOf(fieldNode.asDouble());
        }
        return null;
    }

    /**
     * json转换 为指定格式
     * @param jsonNode
     * @return
     */
    public static DifyEndResp fromJsonNode(JsonNode jsonNode) {
        DifyEndResp difyResp = new DifyEndResp();
        // 设置对话ID
        if (jsonNode.has("conversation_id") && jsonNode.get("conversation_id") != null) {
            difyResp.setConversation_id(jsonNode.get("conversation_id").asText());
        } else {
            difyResp.setConversation_id("");
        }
        // 设置消息ID
        if (jsonNode.has("message_id") && jsonNode.get("message_id") != null) {
            difyResp.setMessage_id(jsonNode.get("message_id").asText());
        } else {
            difyResp.setMessage_id("");
        }
        // 设置ID
        if (jsonNode.has("id") && jsonNode.get("id") != null) {
            difyResp.setId(jsonNode.get("id").asText());
        } else {
            difyResp.setId("");
        }
        // 设置创建时间
        difyResp.setCreated_at(new Date());

        // 价格相关信息
        DifyEndResp.UsageMetadata usageMetadata = new DifyEndResp.UsageMetadata();
        JsonNode metadata = jsonNode.get("metadata");
        if (metadata != null) {
            // 设置提示词令牌数量
            if (metadata.has("prompt_tokens") && metadata.get("prompt_tokens") != null) {
                usageMetadata.setPrompt_tokens(metadata.get("prompt_tokens").asInt());
            } else {
                usageMetadata.setPrompt_tokens(0);
            }
            // 设置提示词单价
            if (metadata.has("prompt_unit_price") && metadata.get("prompt_unit_price") != null) {
                usageMetadata.setPrompt_unit_price(metadata.get("prompt_unit_price").asDouble());
            } else {
                usageMetadata.setPrompt_unit_price(0.0);
            }
            // 设置提示词价格单位
            if (metadata.has("prompt_price_unit") && metadata.get("prompt_price_unit") != null) {
                usageMetadata.setPrompt_price_unit(metadata.get("prompt_price_unit").asDouble());
            } else {
                usageMetadata.setPrompt_price_unit(0.0);
            }
            // 设置提示词价格
            if (metadata.has("prompt_price") && metadata.get("prompt_price") != null) {
                usageMetadata.setPrompt_price(metadata.get("prompt_price").asDouble());
            } else {
                usageMetadata.setPrompt_price(0.0);
            }
            // 设置完成内容令牌数量
            if (metadata.has("completion_tokens") && metadata.get("completion_tokens") != null) {
                usageMetadata.setCompletion_tokens(metadata.get("completion_tokens").asInt());
            } else {
                usageMetadata.setCompletion_tokens(0);
            }
            // 设置完成内容单价
            if (metadata.has("completion_unit_price") && metadata.get("completion_unit_price") != null) {
                usageMetadata.setCompletion_unit_price(metadata.get("completion_unit_price").asDouble());
            } else {
                usageMetadata.setCompletion_unit_price(0.0);
            }
            // 设置完成内容价格单位
            if (metadata.has("completion_price_unit") && metadata.get("completion_price_unit") != null) {
                usageMetadata.setCompletion_price_unit(metadata.get("completion_price_unit").asDouble());
            } else {
                usageMetadata.setCompletion_price_unit(0.0);
            }
            // 设置完成内容价格
            if (metadata.has("completion_price") && metadata.get("completion_price") != null) {
                usageMetadata.setCompletion_price(metadata.get("completion_price").asDouble());
            } else {
                usageMetadata.setCompletion_price(0.0);
            }
            // 设置总令牌数量
            if (metadata.has("total_tokens") && metadata.get("total_tokens") != null) {
                usageMetadata.setTotal_tokens(metadata.get("total_tokens").asInt());
            } else {
                usageMetadata.setTotal_tokens(0);
            }
            // 设置总价格
            if (metadata.has("total_price") && metadata.get("total_price") != null) {
                usageMetadata.setTotal_price(metadata.get("total_price").asDouble());
            } else {
                usageMetadata.setTotal_price(0.0);
            }
            // 设置货币类型
            if (metadata.has("currency") && metadata.get("currency") != null) {
                usageMetadata.setCurrency(metadata.get("currency").asText());
            } else {
                usageMetadata.setCurrency("");
            }
            // 设置延迟时间
            if (metadata.has("latency") && metadata.get("latency") != null) {
                usageMetadata.setLatency(metadata.get("latency").asDouble());
            } else {
                usageMetadata.setLatency(0.0);
            }
        } else {
            // 若 metadata 为 null，使用默认值
            usageMetadata.setPrompt_tokens(0);
            usageMetadata.setPrompt_unit_price(0.0);
            usageMetadata.setPrompt_price_unit(0.0);
            usageMetadata.setPrompt_price(0.0);
            usageMetadata.setCompletion_tokens(0);
            usageMetadata.setCompletion_unit_price(0.0);
            usageMetadata.setCompletion_price_unit(0.0);
            usageMetadata.setCompletion_price(0.0);
            usageMetadata.setTotal_tokens(0);
            usageMetadata.setTotal_price(0.0);
            usageMetadata.setCurrency("");
            usageMetadata.setLatency(0.0);
        }
        difyResp.setMetadata(usageMetadata);
        return difyResp;
    }

    /**
     * 解析返回的do名称列表
     * @param json
     * @return
     */
    //返回的内容不确定，需要解析List
    public static List<String> convertJsonToNameList(String json) {
        //替换错误引号
        json = json.replace('“', '"').replace('”', '"');
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 尝试解析为 List<String> 格式
            List<String> nameList = objectMapper.readValue(json, ArrayList.class);
            if (!nameList.isEmpty() && nameList.get(0) instanceof String) {
                return nameList;
            }
        } catch (IOException e) {
            // 若第一种格式解析失败，尝试第二种格式
            try {
                Map<String, List<String>> map = objectMapper.readValue(json, Map.class);
                for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                    List<String> value = entry.getValue();
                    if (!value.isEmpty() && value.get(0) instanceof String) {
                        return value;
                    }
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return new ArrayList<>();
    }

}
